package cc.smarnet.caihou.phone.deliver;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.entity.Deliver;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 新增出库品种的activity
 */
public class DeliverVarietyAddActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private Spinner classesSpinner;//等级
    private Spinner flowerPoleLengthSpinner;//花杆长度
    private Spinner packingSpecificationsSpinner;//规格
    private Spinner varietySpinner;//品种
    private TextView varietyCodeTextView;//品种编码;
    private EditText numberEditText;//数量;
    private Button confirmButton;
    private ProgressBar progressBar;

    Deliver deliver;

    private String token;

    List<String> varietyList = new ArrayList<>();
    List<String> varietyCodeList = new ArrayList<>();
    List<String> packingSpecificationsList = new ArrayList<>();
    List<String> classesList = new ArrayList<>();
    List<String> flowerPoleLengthList = new ArrayList<>();


    private String classes; // 等级
    private String flowerPoleLength; // 花杆长度
    private String number; // 数量(扎)
    private String packingSpecifications; // 规格
    private String variety;//品种
    private String varietyCode; // 品种编码

    int mYear, mMonth, mDay;

    private final String basePath = "/sys/dict/getDictItems";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver_variety_add);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        progressBar.setVisibility(View.GONE);

        //获取从DeliverDetailActivity中传过来的值
        deliver = (Deliver) getIntent().getSerializableExtra("deliverDetail");
        getToken();

        getVariety();//获取品种
        getPackingSpecifications();//获取规格
        getClasses();//获取等级
        getFlowerPoleLength();// 获取花杆长度

        // 点击确认按钮的监听
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取入库数量
                if (numberEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyAddActivity.this).create();
                    alertDialog.setMessage("请输入数量！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                } else {
                    number = numberEditText.getText().toString();
                }

                // 新增入库信息
                addDeliverVariety();
            }
        });
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initViews() {
        imageButton = findViewById(R.id.deliver_variety_add_return);
        classesSpinner = findViewById(R.id.deliver_variety_add_classes_spinner);
        flowerPoleLengthSpinner = findViewById(R.id.deliver_variety_add_flowerPoleLength_spinner);
        packingSpecificationsSpinner = findViewById(R.id.deliver_variety_add_packingSpecifications_spinner);
        varietySpinner = findViewById(R.id.deliver_variety_add_variety_spinner);
        varietyCodeTextView = findViewById(R.id.deliver_variety_add_varietyCode_textView);
        numberEditText = findViewById(R.id.deliver_variety_add_number_editText);
        confirmButton = findViewById(R.id.deliver_variety_confirm_add_button);
        progressBar = findViewById(R.id.deliver_variety_add_progressBar);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }


    // 获取采收品种
    public void getVariety() {
        String url = IPConfig.baseUrl + "/flower/flowerVariety/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DeliverVarietyAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                varietyList.add(name);
                                // 获取品种编码
                                String code=jsonObj.getString("code");
                                varietyCodeList.add(code);
                            }

                            if (varietyList.size() > 0) {
                                variety = varietyList.get(0);// 设置默认的采收品种
                                varietyCode = varietyCodeList.get(0);// 设置默认的品种编码
                                varietyCodeTextView.setText(varietyCode);
                                varietySpinner();
                            }
                        }
                    }
                });
    }

    // 获取打包规格
    public void getPackingSpecifications() {
        String url = IPConfig.baseUrl + basePath + "/planting_packing_specifications";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DeliverVarietyAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                packingSpecificationsList.add(name);
                            }

                            if (packingSpecificationsList.size() > 0) {
                                packingSpecifications = packingSpecificationsList.get(0);// 设置默认的打包规格
                                packingSpecificationsSpinner();
                            }
                        }
                    }
                });
    }

    // 获取等级
    public void getClasses() {
        String url = IPConfig.baseUrl + basePath + "/planting_flower_level";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DeliverVarietyAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                classesList.add(name);
                            }

                            if (classesList.size() > 0) {
                                classes = classesList.get(0);// 设置默认的打包规格
                                classesSpinner();
                            }
                        }
                    }
                });
    }

    // 获取花杆长度
    public void getFlowerPoleLength() {
        String url = IPConfig.baseUrl + basePath + "/planting_flower_pole";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DeliverVarietyAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                flowerPoleLengthList.add(name);
                            }

                            if (flowerPoleLengthList.size() > 0) {
                                flowerPoleLength = flowerPoleLengthList.get(0);// 设置默认的花杆长度
                                flowerPoleLengthSpinner();
                            }
                        }
                    }
                });
    }

    //采收品种的spinner
    public void varietySpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, varietyList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        varietySpinner.setAdapter(adapter);
        varietySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                variety = varietyList.get(i);
                varietyCode=varietyCodeList.get(i);
                varietyCodeTextView.setText(varietyCode);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //打包规格的spinner
    public void packingSpecificationsSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, packingSpecificationsList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        packingSpecificationsSpinner.setAdapter(adapter);
        packingSpecificationsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                packingSpecifications = packingSpecificationsList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //等级的spinner
    public void classesSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, classesList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classesSpinner.setAdapter(adapter);
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                classes = classesList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //花杆长度的spinner
    public void flowerPoleLengthSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, flowerPoleLengthList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerPoleLengthSpinner.setAdapter(adapter);
        flowerPoleLengthSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                flowerPoleLength = flowerPoleLengthList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }


    // 新增出库品种信息
    public void addDeliverVariety() {
        confirmButton.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("variety", variety);//品种
        map.put("varietyCode", varietyCode);//品种编码
        map.put("packingSpecifications", packingSpecifications);//规格
        map.put("classes", classes);//等级
        map.put("flowerPoleLength", flowerPoleLength);//花杆长度
        map.put("number", number);//数量
        map.put("orderId", deliver.getId());//订单id
        String requestJsonString = JSON.toJSONString(map);
        String url = IPConfig.baseUrl + "/flower/flowerOutorderinfo/add";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .content(requestJsonString)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        confirmButton.setClickable(true);
                        Toast.makeText(DeliverVarietyAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyAddActivity.this).create();
                            alertDialog.setMessage("出库品种新增成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(DeliverVarietyAddActivity.this, DeliverDetailActivity.class);
                                    intent.putExtra("deliverDetail", (Serializable) deliver);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }
}